<script setup lang="ts">
import type { WaterFallsFlow } from "@/typings/comps/comps";

/**
 * @description {Component} CustomWaterfallsFlow 瀑布流组件
 * @prop {any[]} data 瀑布流列表数据
 * @prop {number} columnCount 列数
 * @prop {string} bgColor 背景颜色
 * @prop {string} height 容器高度
 * @prop {string} padding 内边距
 * @prop {string} columnGap 竖向列间距
 * @prop {string} rowGap 横向列间距
 * @prop {string} keyName 指定虚拟 dom 的 keyName
 * @slot {item} 列表项内容插槽，<template #item="{ row }"></template>
 * @emit {Function} clickWrapper 点击列表项卡片事件
 * @author 花东红
 * @time 2025/8/1
 */
const props = withDefaults(defineProps<WaterFallsFlow.Props>(), {
  data: () => [],
  columnCount: 2,
  bgColor: "#F3F4F7",
  height: "fit-content",
  padding: "20rpx",
  columnGap: "20rpx",
  rowGap: "10rpx",
  keyName: ""
});

const emit = defineEmits(["clickWrapper", "scrollToLower"]);

const dataList = ref<WaterFallsFlow.initialStateType>([]);

const rowWidth = computed(() => `calc(100% / ${props.columnCount} -  ${props.rowGap} )`);

const isEven = computed(() => props.columnCount % 2 === 0);

watch(
  () => props.data,
  (newList) => {
    generateData(newList);
  },
  { deep: true }
);

watch(
  () => props.columnCount,
  () => {
    generateData(props.data);
  }
);

const generateData = (items: any[]) => {
  const cols = Array.from({ length: props.columnCount }, () => []);

  items.forEach((item) => {
    const shortestCol = cols.reduce((min, col, idx) => (col.length < cols[min].length ? idx : min), 0);
    cols[shortestCol].push(item as never);
  });
  dataList.value = cols;
};

const clickWrapper = (item: Record<string, any>) => {
  emit("clickWrapper", item);
};
</script>

<template>
  <view :style="{ height: props.height, backgroundColor: props.bgColor, padding: props.padding }">
    <view :class="[`w-full flex bg-transparent ${isEven ? 'justify-between' : 'justify-center'}`]">
      <view v-for="(col, index) in dataList" :key="index" class="w-full flex flex-col" :style="{ width: rowWidth, gap: props.columnGap }">
        <view v-for="(item, i) in col" :key="props.keyName ? item[props.keyName] : i" class="w-full h-auto" @tap="clickWrapper(item)">
          <slot name="item" :row="item" :index="i"></slot>
        </view>
      </view>
    </view>
  </view>
</template>
